<template>
  <div class="forum-container">
    <!-- 欢迎区域 -->
    <div class="welcome-section glassmorphism">
      <div class="welcome-content">
        <div class="welcome-text">
          <h1 class="welcome-title">学院论坛</h1>
          <p class="welcome-description">欢迎来到学院论坛，这里是交流学习、分享经验的平台。发布你的想法，与同学们一起探讨学术问题，分享你的学习心得。</p>
          <el-button type="primary" class="publish-btn" @click="goToPublish">立即发帖</el-button>
        </div>
        <div class="welcome-image">
          <img src="../../assets/forum/forum-welcome.svg" alt="论坛欢迎图" class="rounded-image" />
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section glassmorphism">
      <div class="section-header">
        <h2 class="section-title">热门讨论</h2>
        <div class="filter-controls">
          <el-radio-group v-model="sortType" size="small" @change="resetAndLoadPosts">
            <el-radio-button label="latest">最新</el-radio-button>
            <el-radio-button label="hot">热门</el-radio-button>
          </el-radio-group>

          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索帖子"
              prefix-icon="el-icon-search"
              size="small"
              clearable
              @clear="resetAndLoadPosts"
              @keyup.enter.native="searchPosts"
            ></el-input>
          </div>
        </div>
      </div>
    </div>

    <!-- 帖子列表区域 -->
    <div class="post-list-container" ref="postListContainer" @scroll="handleScroll">
      <!-- 分页指示器 -->
      <div class="pagination-indicator" v-if="posts.length > 0">
        <span>当前加载第 {{ Math.ceil(posts.length / pageSize) }} 页 (共{{ posts.length }}个帖子)</span>
      </div>
      <div v-if="loading && posts.length === 0" class="loading-placeholder">
        <div class="loading-spinner">
          <i class="el-icon-loading"></i>
        </div>
        <p>正在加载帖子...</p>
      </div>

      <div v-else-if="posts.length === 0" class="empty-placeholder">
        <i class="el-icon-chat-dot-square"></i>
        <p>暂无帖子，快来发布第一个话题吧！</p>
      </div>

      <div v-else class="post-grid">
        <div
          v-for="(post, index) in posts"
          :key="post.tipId"
          class="post-card glassmorphism card-hover"
          @click="viewPostDetail(post.tipId)"
        >
          <!-- 帖子封面图 -->
          <div class="post-cover">
            <img
              :src="post.tipPictrue || require('@/assets/no-image.png')"
              :alt="post.tipTitel"
              class="cover-image"
            >
          </div>

          <!-- 帖子内容 -->
          <div class="post-content">
            <h3 class="post-title">{{ post.tipTitel }}</h3>

            <div class="post-meta">
              <div class="author-info">
                <el-avatar :size="24" :src="post.tipUserPic" class="author-avatar"></el-avatar>
                <span class="author-name">{{ post.tipUserN }}</span>
                <span class="user-rank" :class="getRankClass(post.userRank)">
                  {{ getRankLabel(post.userRank) }}
                </span>
              </div>

              <div class="post-category" v-if="post.tipTypeId">
                <span class="category-tag">{{ getTypeName(post.tipTypeId) }}</span>
              </div>
            </div>

            <div class="post-footer">
              <div class="post-stats">
                <span class="stat-item">
                  <i class="el-icon-view"></i> {{ post.tipViews }}
                </span>
                <span class="stat-item">
                  <i class="el-icon-star-off"></i> {{ post.tipGoods }}
                </span>
                <span class="stat-item">
                  <i class="el-icon-chat-dot-round"></i> {{ post.tipComments }}
                </span>
              </div>
              <div class="post-time">{{ formatTime(post.tipTime) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部加载更多 -->
      <div v-if="loading && posts.length > 0" class="bottom-loading">
        <i class="el-icon-loading"></i>
        <span>加载更多...</span>
      </div>

      <div v-if="!loading && !hasMore && posts.length > 0" class="no-more">
        <span>没有更多帖子了</span>
      </div>
    </div>
  </div>
</template>

<script>
import { alltip, alltipByTime, searchTip } from '@/api/api';

export default {
  name: 'ForumIndex',
  data() {
    return {
      posts: [],
      currentPage: 1,
      pageSize: 16, // 每页显示16个帖子（四行，每行四个）
      loading: false,
      hasMore: true,
      sortType: 'hot', // 'hot' 或 'new'
      searchKeyword: '',
      isSearching: false,
      scrollPosition: 0,
      isInitialLoad: true
    };
  },
  created() {
    // 从缓存中恢复状态
    this.restoreState();
  },
  mounted() {
    // 如果是初次加载，则获取帖子
    if (this.isInitialLoad) {
        console.log('加载帖子...');
      this.loadPosts();
      this.isInitialLoad = false;
    } else {
      // 恢复滚动位置
      this.$nextTick(() => {
        if (this.$refs.postListContainer) {
          this.$refs.postListContainer.scrollTop = this.scrollPosition;
        }
      });
    }
  },
  beforeRouteLeave(to, from, next) {
    // 保存当前状态到缓存
    this.saveState();
    next();
  },
  methods: {
    // 加载帖子
    async loadPosts() {
      if (this.loading || !this.hasMore) {
        console.log('跳过加载：', this.loading ? '正在加载中' : '没有更多数据');
        return;
      }
      console.log('开始加载帖子，当前页码：', this.currentPage, '每页数量：', this.pageSize);
      this.loading = true;
      try {
        let response;
        const params = {
          PageNumber: this.currentPage,
          PageSize: this.pageSize
        };

        if (this.isSearching && this.searchKeyword) {
          // 搜索帖子
          response = await searchTip({
              all: this.searchKeyword,
              PageNumber: this.currentPage,
              PageSize: this.pageSize,
          });
        } else if (this.sortType === 'hot') {
          // 按热度排序
          response = await alltip(params);
          console.log(response)
        } else {
          // 按时间排序
          response = await alltipByTime(params);
        }

        if (response.data.message === "成功") {
          const newPosts = response.data.data.list || [];
          console.log('获取到新帖子数量：', newPosts.length);

          // 将新帖子添加到列表中
          this.posts = [...this.posts, ...newPosts];

          // 判断是否还有更多帖子
          this.hasMore = newPosts.length >= this.pageSize;
          console.log('是否还有更多帖子：', this.hasMore);

          // 页码加1
          this.currentPage++;
          console.log('更新后的页码：', this.currentPage);
        } else {
          this.$message.error('获取帖子失败：' + response.data.msg);
          this.hasMore = false;
        }
      } catch (error) {
        console.error('加载帖子出错：', error);
        this.$message.error('加载帖子出错，请稍后重试');
        this.hasMore = false;
      } finally {
        this.loading = false;
      }
    },

    // 处理滚动事件
    handleScroll(e) {
      // 保存当前滚动位置
      this.scrollPosition = e.target.scrollTop;

      // 检查是否滚动到底部
      const { scrollTop, scrollHeight, clientHeight } = e.target;
      const bottomThreshold = 200; // 增加阈值，提前触发加载，使滚动更流畅

      if (scrollHeight - scrollTop - clientHeight < bottomThreshold && !this.loading && this.hasMore) {
        console.log('触发加载更多，距离底部：', scrollHeight - scrollTop - clientHeight);
        this.loadPosts();
      }
    },

    // 重置并重新加载帖子
    resetAndLoadPosts() {
      this.posts = [];
      this.currentPage = 1;
      this.hasMore = true;
      this.isSearching = false;
      this.scrollPosition = 0; // 重置滚动位置

      // 重置滚动位置
      this.$nextTick(() => {
        if (this.$refs.postListContainer) {
          this.$refs.postListContainer.scrollTop = 0;
        }
      });

      this.loadPosts();
    },

    // 搜索帖子
    searchPosts() {
      if (!this.searchKeyword.trim()) {
        // 如果搜索关键词为空，恢复正常列表
        if (this.isSearching) {
          this.isSearching = false;
          this.resetAndLoadPosts();
        }
        return;
      }

      this.isSearching = true;
      this.posts = [];
      this.currentPage = 1;
      this.hasMore = true;
      this.scrollPosition = 0; // 重置滚动位置

      // 重置滚动位置
      this.$nextTick(() => {
        if (this.$refs.postListContainer) {
          this.$refs.postListContainer.scrollTop = 0;
        }
      });

      this.loadPosts();
    },

    // 跳转到发布页面
    goToPublish() {
      this.$router.push('/Main/forum/publish');
    },

    // 查看帖子详情
    viewPostDetail(tipId) {
      this.$router.push({
        path: '/Main/forum/detail',
        query: { id: tipId }
      });
    },

    // 根据帖子类型ID获取类型名称
    getTypeName(tipTypeId) {
      // 从store中获取帖子类型列表
      const tipTypeList = this.$store.state.tipTypeList;

      // 如果store中没有帖子类型数据，则触发获取
      if (tipTypeList.length === 0) {
        this.$store.dispatch('fetchTipTypes');
        return '加载中...';
      }
      // 查找对应的帖子类型
      const tipType = tipTypeList.find(type => type.tipTypeId === tipTypeId);
      return tipType ? tipType.tipTypeName : '未知类型';
    },

    // 格式化时间
    formatTime(timeString) {
      if (!timeString) return '';

      const date = new Date(timeString);
      const now = new Date();
      const diff = now - date;

      // 小于1分钟
      if (diff < 60 * 1000) {
        return '刚刚';
      }

      // 小于1小时
      if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前';
      }

      // 小于1天
      if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
      }

      // 小于30天
      if (diff < 30 * 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前';
      }

      // 大于30天，显示具体日期
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    },

    // 获取用户等级样式
    getRankClass(rank) {
      if (!rank) return 'rank-0';

      if (rank < 100) return 'rank-d'; // D级 - 绿色
      if (rank < 500) return 'rank-c'; // C级 - 蓝色
      if (rank < 1000) return 'rank-b'; // B级 - 紫色
      if (rank < 2000) return 'rank-a'; // A级 - 红色
      return 'rank-s'; // S级 - 金色
    },

    // 获取用户等级标签
    getRankLabel(rank) {
      if (!rank) return '新手';

      if (rank < 100) return '初级魔王';
      if (rank < 500) return '中级魔王';
      if (rank < 1000) return '高级魔王';
      if (rank < 2000) return '资深魔王';
      return 'xk';
    },

    // 保存状态到缓存
    saveState() {
      // 只保存最多30个帖子，避免缓存过大
      const postsToSave = this.posts.slice(0, 30);

      const state = {
        posts: postsToSave,
        currentPage: this.currentPage,
        hasMore: this.hasMore,
        sortType: this.sortType,
        searchKeyword: this.searchKeyword,
        isSearching: this.isSearching,
        scrollPosition: this.scrollPosition,
        pageSize: this.pageSize,
        isInitialLoad: false,
        totalPosts: this.posts.length // 记录总帖子数，用于恢复时的参考
      };

      console.log('保存状态：', state);
      sessionStorage.setItem('forumState', JSON.stringify(state));
    },

    // 从缓存恢复状态
    restoreState() {
      const savedState = sessionStorage.getItem('forumState');

      if (savedState) {
        try {
          const state = JSON.parse(savedState);
          console.log('恢复状态：', state);

          this.posts = state.posts || [];
          this.currentPage = state.currentPage || 1;
          this.hasMore = state.hasMore !== undefined ? state.hasMore : true;
          this.sortType = state.sortType || 'hot';
          this.searchKeyword = state.searchKeyword || '';
          this.isSearching = state.isSearching || false;
          this.scrollPosition = state.scrollPosition || 0;

          // 恢复页面大小设置（如果存在）
          if (state.pageSize) {
            this.pageSize = state.pageSize;
          }

          this.isInitialLoad = state.isInitialLoad !== undefined ? state.isInitialLoad : true;

          // 如果保存的帖子数量与总数不一致，可能需要重新加载
          if (state.totalPosts && state.totalPosts > this.posts.length) {
            console.log('保存的帖子总数与当前不一致，可能需要加载更多');
          }
        } catch (error) {
          console.error('恢复状态出错：', error);
          // 出错时重置状态
          this.resetState();
        }
      }
    },

    // 重置状态
    resetState() {
      this.posts = [];
      this.currentPage = 1;
      this.hasMore = true;
      this.sortType = 'hot';
      this.searchKeyword = '';
      this.isSearching = false;
      this.scrollPosition = 0;
      this.isInitialLoad = true;
    }
  }
};
</script>

<style scoped>
.forum-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f7fa;
  font-family: 'Noto Sans SC', sans-serif;
  padding: 20px;
}

/* 玻璃态效果 */
.glassmorphism {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
}

/* 卡片悬浮效果 */
.card-hover {
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 28px 0 rgba(31, 38, 135, 0.15);
}

/* 欢迎区域样式 */
.welcome-section {
  margin-bottom: 30px;
  padding: 30px;
}

.welcome-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.welcome-text {
  flex: 1;
  padding-right: 30px;
}

.welcome-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 15px;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.welcome-description {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
  line-height: 1.6;
}

.welcome-image {
  flex: 1;
  display: flex;
  justify-content: center;
}

.rounded-image {
  border-radius: 12px;
  max-width: 100%;
  height: auto;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 30px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-title {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.filter-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-box {
  width: 250px;
}

.publish-btn {
  font-weight: bold;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  border: none;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.publish-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08);
}

.post-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  position: relative;
  height: calc(100vh - 300px); /* 调整高度以适应新的欢迎区域 */
  min-height: 700px; /* 确保容器有最小高度 */
  overscroll-behavior: contain; /* 防止滚动传播 */
}

.post-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 每行固定4个元素 */
  grid-template-rows: repeat(4, auto); /* 四行布局 */
  gap: 20px;
  margin-bottom: 20px; /* 底部间距，方便查看加载状态 */
}

.post-card {
  overflow: hidden;
  cursor: pointer;
}

.post-cover {
  height: 160px;
  overflow: hidden;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.post-card:hover .cover-image {
  transform: scale(1.05);
}

.post-content {
  padding: 15px;
}

.post-title {
  margin: 0 0 12px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  line-height: 1.4;
  height: 44px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.author-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.author-avatar {
  margin-right: 8px;
}

.author-name {
  font-size: 13px;
  color: #606266;
  margin-right: 5px;
  font-weight: 500;
}

.post-category {
  margin-left: auto;
}

.category-tag {
  display: inline-block;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  background: rgba(79, 70, 229, 0.1);
  color: #4f46e5;
  font-weight: 500;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-rank {
  display: inline-block;
  font-size: 11px;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: 4px;
  color: white;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  vertical-align: middle;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5px;
}

.rank-0 {
  background: linear-gradient(135deg, #9e9e9e, #616161); /* 灰色，用于新手 */
}

.rank-d {
  background: linear-gradient(135deg, #4caf50, #2e7d32);
}

.rank-c {
  background: linear-gradient(135deg, #2196f3, #0d47a1);
}

.rank-b {
  background: linear-gradient(135deg, #9c27b0, #4a148c);
}

.rank-a {
  background: linear-gradient(135deg, #f44336, #b71c1c); /* 红色 */
}

.rank-a-plus {
  background: linear-gradient(135deg, #ff5722, #d84315); /* 深橙色，作为备用 */
}

.rank-s {
  background: linear-gradient(135deg, #ffd700, #ff6f00);
  color: #5d4037;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
}

.post-stats {
  display: flex;
  gap: 12px;
}

.stat-item {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  transition: color 0.2s;
}

.stat-item i {
  margin-right: 4px;
  opacity: 0.7;
  transition: opacity 0.2s;
}

.stat-item:hover {
  color: #4f46e5;
}

.stat-item:hover i {
  opacity: 1;
}

.post-time {
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

.loading-placeholder,
.empty-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #909399;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 12px;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.loading-placeholder i,
.empty-placeholder i {
  font-size: 48px;
  margin-bottom: 20px;
  color: #4f46e5;
  opacity: 0.7;
}

.bottom-loading,
.no-more {
  text-align: center;
  padding: 20px 0;
  color: #909399;
  font-size: 14px;
  font-weight: 500;
}

.bottom-loading i {
  margin-right: 8px;
  color: #4f46e5;
}

.pagination-indicator {
  position: fixed;
  top: 120px;
  right: 20px;
  background: rgba(79, 70, 229, 0.8);
  color: white;
  padding: 8px 15px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  z-index: 100;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
  transition: all 0.3s;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.pagination-indicator:hover {
  background: rgba(79, 70, 229, 0.9);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}
</style>
